import React, { useContext, Fragment, useState, useEffect } from "react";
import Link from "next/link";
import CartContext from "../../helpers/cart";
import { Media } from "reactstrap";
import { CurrencyContext } from "../../helpers/Currency/CurrencyContext";
import { getCartInfo, removeCartProduct } from "../../api/api"
import { fileServerUrl } from "../../config/index.json";
import { getTwoDecimal } from "../../tools/tools";
import { toast } from "react-toastify";
import { useRouter } from 'next/router';

const CartComponent = ({ icon, layout }) => {
  const router = useRouter();

  const context = useContext(CartContext);
  const currContext = useContext(CurrencyContext);
  const symbol = currContext.state.symbol;
  // const cartList = context.state;
  // const total = context.cartTotal;
  const removeFromCart = context.removeFromCart;
  const [openSide, setOpenSide] = useState(false);

  const [cartList, setCartList] = useState([]);
  const [catNum, setCartNum] = useState('0');
  const [total, setTotal] = useState(0);

  useEffect(() => {
    if (openSide) {
      var userInfo = localStorage.getItem("XYCLogin");
      if (userInfo) {
        console.log(JSON.parse(userInfo).user_guid)
        if (JSON.parse(userInfo).user_guid) {
          getCartInfo({ userGuid: JSON.parse(userInfo).user_guid }).then(res => {
            setCartList(res.data);
            setCartNum(res.data.length);
            localStorage.setItem('cartNum', res.data.length);
            let to = Number(0);
            res.data.map(item => {
              to += parseFloat(item.price * item.quantity);
            })
            setTotal(getTwoDecimal(`${to}`));
          });
        }
      }
    }
  }, [openSide])

  useEffect(() => {
    var userInfo = localStorage.getItem("XYCLogin");
    if (userInfo) {
      if (JSON.parse(userInfo).user_guid) {
        getCartInfo({ userGuid: JSON.parse(userInfo).user_guid }).then(res => {
          setCartList(res.data);
          setCartNum(res.data.length);
          localStorage.setItem('cartNum', res.data.length);
          let to = Number(0);
          res.data.map(item => {
            to += parseFloat(item.price * item.quantity);
          })
          setTotal(getTwoDecimal(`${to}`));
        });
      }
    }
  }, [window.onload])

  const removeProduct = (item) => {
    var count = cartList.filter(p => p.product_id != item.product_id);
    setCartList(v => v.filter(p => p.product_id != item.product_id));
    setCartNum(count.length);
    localStorage.setItem('cartNum', count.length);

    removeCartProduct({ "product_id": item.product_id });
    toast.success("Product remove succeed!");
  }

  useEffect(() => {
    const handleStorageChange = (event) => {
      if (event.key === 'cartNum') {
        console.log(localStorage.getItem('cartNum'))
        setCartNum(localStorage.getItem('cartNum'));
      }
    };
    window.addEventListener('storage', handleStorageChange);

    return () => {
      window.removeEventListener('storage', handleStorageChange);
    };
  })

  return (
    <Fragment>
      {
        <li
          className="onhover-div mobile-cart"
          onClick={() => setOpenSide(true)}
        >
          <div className="cart-qty-cls">{catNum}</div>
          <div href={null}>
            <Media
              alt="cart"
              src={icon.src}
              className="img-fluid blur-up lazyload"
            />
            <i style={{ fontSize: 20, marginRight: -10 }} className="fa fa-shopping-cart"></i>
          </div>
        </li>
      }
      <div
        id="cart_side"
        className={`add_to_cart ${layout} ${openSide ? "open-side" : ""} `}
      >
        <a href={null} className="overlay"></a>
        <div className="cart-inner">
          <div className="cart_top">
            <h3>my cart</h3>
            <div className="close-cart" onClick={() => setOpenSide(false)}>
              <a href={null}>
                <i className="fa fa-times" aria-hidden="true"></i>
              </a>
            </div>
          </div>
          <div className="cart_media">
            <ul className="cart_product">
              {cartList.length > 0 &&
                cartList.map((item, index) => (
                  <div>
                    <li key={`cart-popup-${index}`}>
                      <div className="media">
                        <a href={null}>
                          <Media
                            alt=""
                            className="mr-3"
                            onClick={() => {
                              router.push(`/product-details/${item.product_id}`)
                            }}
                            src={item.product_media1 ? `${fileServerUrl}/${item.product_media1}` : `${fileServerUrl}/products/default.jpg`}
                          />
                        </a>
                        <div className="media-body">
                          <a href={null}>
                            <h4>{item.product_name}</h4>
                          </a>
                          <h4>
                            <span>
                              {item.quantity} x {symbol} {getTwoDecimal(item.price)}
                            </span>
                          </h4>
                        </div>
                      </div>
                      <div className="close-circle">
                        <a href="#" onClick={() => removeProduct(item)}>
                          <i className="fa fa-trash" aria-hidden="true"></i>
                        </a>
                      </div>
                    </li>
                  </div>
                ))}
            </ul>
            <ul className="cart_total">
              <li>
                <div className="total">
                  <h5>
                    subtotal : <span>${total}</span>
                  </h5>
                </div>
              </li>
              <li>
                <div>
                  <Link href="/page/account/cart">
                    <a className="btn btn-solid btn-xs view-cart">view cart</a>
                  </Link>
                </div>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </Fragment>
  );
};

export default CartComponent;
